//
//  PreLoginCodeVC.m
//  safeLady
//
//  Created by Justsoso on 2017/6/13.
//  Copyright © 2017年 xmy. All rights reserved.
//

#import "PreLoginCodeVC.h"
#import "PreLoginViewModel.h"

@interface PreLoginCodeVC (){
    UIImageView *navBarHairlinewImageView;
}

@property (weak, nonatomic) IBOutlet UIButton *backBtn;
@property (weak, nonatomic) IBOutlet UILabel *phoneLabel;
@property (weak, nonatomic) IBOutlet UIButton *getCodeButton;
@property (weak, nonatomic) IBOutlet UITextField *codeTextField;
@property (weak, nonatomic) IBOutlet UILabel *getCodeTitle;

@property (weak, nonatomic) IBOutlet UIView *codeInputView;
@property (weak, nonatomic) IBOutlet UILabel *codeLabel1;
@property (weak, nonatomic) IBOutlet UILabel *codeLabel2;
@property (weak, nonatomic) IBOutlet UILabel *codeLabel3;
@property (weak, nonatomic) IBOutlet UILabel *codeLabel4;

@property (nonatomic, strong) NSString *codeStr;
@property (nonatomic, strong) NSTimer *codeTimer;
@property (nonatomic, strong) NSNumber *littleTime;
@property (nonatomic, strong) NSArray *codeLabelArr;
@property (nonatomic, strong) NSString *phone;


@property (nonatomic, strong) PreLoginViewModel *viewModel;

@end

@implementation PreLoginCodeVC

@synthesize viewModel = _viewModel;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self.navigationController.navigationBar setHidden:YES];
    
    self.codeInputView.layer.cornerRadius = 15;
    self.codeInputView.layer.masksToBounds = YES;
    self.codeInputView.layer.shadowOpacity = 0.5;
    self.codeInputView.layer.shadowColor = [UIColor grayColor].CGColor;
    self.codeInputView.layer.shadowOffset = CGSizeMake(1, 1);
    self.codeInputView.layer.masksToBounds = NO;
    
    [self setLabelBorder:self.codeLabel1];
    [self setLabelBorder:self.codeLabel2];
    [self setLabelBorder:self.codeLabel3];
    [self setLabelBorder:self.codeLabel4];
    
    [self getCode];
    self.codeTextField.maxLenght = 4;
    [self.codeTextField becomeFirstResponder];
    self.codeLabelArr = @[self.codeLabel1,self.codeLabel2,self.codeLabel3,self.codeLabel4];
    @weakify(self);
    [self.codeInputView setTapActionWithBlock:^(UIGestureRecognizer *gestureRecoginzer) {
        [self.codeTextField becomeFirstResponder];
    }];
    self.phoneLabel.text = self.phone;
    [self.getCodeButton addTarget:self action:@selector(getCode) forControlEvents:UIControlEventTouchUpInside];
    RAC(self.getCodeButton,enabled) = [RACObserve(self, littleTime) map:^id(NSString *text) {
        return @([text integerValue] == 0);
    }];
    RACSignal *validLoginSignal = [self.codeTextField.rac_textSignal
                                   filter:^BOOL(NSString *code) {
                                       return code.length == 4;
                                   }];
    [validLoginSignal subscribeNext:^(NSNumber *usernameIsVaild) {
        @strongify(self);
        [self nextStep];
    }];
    [self.codeTextField.rac_textSignal subscribeNext:^(NSString *code) {
        @strongify(self);
        [self checkcodeLabelText:[code length]];
    }];
    
}

- (void)setLabelBorder:(UILabel *)label {
    label.layer.borderWidth = 2;
    label.layer.borderColor = [UIColor lightGrayColor].CGColor;
    label.layer.masksToBounds = YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)bindViewModel {
    [super bindViewModel];
    

//    @weakify(self);
//    RAC(self.viewModel,codeStr) = self.codeTextField.rac_textSignal;
    
//    [[self.codeTextField.rac_keyboardReturnSignal filter:^BOOL(id value) {
//        @strongify(self)
////        return self.LoginTo.enabled;
//        return nil;
//    }] subscribeNext:^(id x) {
//        @strongify(self)
//        [self.viewModel.loginCommand execute:nil];
//        
//    }];
    [[self.backBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        [self.navigationController popViewControllerAnimated:YES];
    }];
    
//    RAC(self.viewModel, codeStr) = self.codeText.
}

//检查验证码输入情况
- (void)checkcodeLabelText:(NSInteger)strLength {
    if ([self.codeTextField.text length] == 0) {
        strLength = 0;
    }
    int number = 0;
    for (UILabel *codeLabel in self.codeLabelArr) {
        if (strLength > number) {
            codeLabel.text = [self.codeTextField.text substringWithRange:NSMakeRange(number, 1)];
        }else {
            codeLabel.text = @"";
        }
        number++;
    }
}

//关闭定时器
- (void)stopTimer {
    if (_codeTimer) {
        [_codeTimer invalidate];
    }
    _codeTimer = nil;
}

//重发秒数倒计时
- (void)changeTimeAtTimedisplay {
    self.littleTime = [NSNumber numberWithInt:self.littleTime.intValue - 1];
    if (self.littleTime.intValue == 0) {
        self.getCodeTitle.text = @"发送验证码";
        self.getCodeTitle.layer.masksToBounds = [self getCodeBorder];
        [self stopTimer];
    }else {
        self.getCodeTitle.text = [NSString stringWithFormat:@"%@秒后可重发",self.littleTime];
    }
}

- (void)nextStep {
    [self.codeTextField resignFirstResponder];
    NSString *codeTextField = self.codeTextField.text;
    if (codeTextField == self.codeStr) {
//        @weakify(self);
        self.viewModel.telePhoneStr = self.phone;
        self.viewModel.codeStr = self.codeStr;
        [self.viewModel.loginCommand execute:nil];
        [self hiddenHUDWithString:@"登录中..." error:YES];
    }else if (codeTextField != self.codeStr){
        [self hiddenHUDWithString:@"输入的验证码有误！" error:YES];
    }
    self.codeTextField.text = @"";
}

//获取验证码
- (void)getCode {
    @weakify(self);
    [self startTimer];
    [[[HttpManagerCenter sharedHttpManager] sendPhoneCode:self.phone resultClass:nil] subscribeNext:^(BaseModel *model) {
        @strongify(self);
        if (model.code == 200) {
            self.codeStr = model.data[@"code"];
        }else {
            [self showRequestErrorMessage:model];
        }
    } error:^(NSError *error) {
        [self hiddenHUDWithString:@"网络链接差,请稍后再试" error:YES];
    } completed:^{
        
    }];
}



- (NSString *)codeStr {
    if (!_codeStr) {
        _codeStr = [NSString new];
    }
    return _codeStr;
}

//懒加载创建定时器
- (NSTimer *)startTimer {
    if (!_codeTimer) {
        self.littleTime = [NSNumber numberWithInt:60];
        
        self.getCodeTitle.layer.masksToBounds = [self getCodeBorder];
        
        _codeTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(changeTimeAtTimedisplay) userInfo:nil repeats:YES];
    }
    return _codeTimer;
}

- (BOOL)getCodeBorder {
    if (!self.getCodeTitle.layer.masksToBounds) {
        self.getCodeTitle.layer.borderWidth = 2;
        self.getCodeTitle.layer.borderColor = [UIColor colorWithHex:0x2a2a2a alpha:1.0].CGColor;
        return YES;
    }else{
        self.getCodeTitle.layer.borderWidth = 0;
        self.getCodeTitle.layer.borderColor = [UIColor colorWithHex:0x2a2a2a alpha:0.0].CGColor;
        return NO;
    }
}

- (PreLoginViewModel *)viewModel {
    if (!_viewModel) {
        _viewModel = [[PreLoginViewModel alloc] initWithViewController:self];
    }
    return _viewModel;
}

//- (void)dealloc {
//    [self stopTimer];
//}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
